import redis

# 创建 Redis 连接
r = redis.Redis(host='127.0.0.1', port=6379, db=2)


def get_from_cache(key):
    value = r.get(key)
    if value:
        return value.decode()
    else:
        return None


def set_to_cache(key, value, expire_time=60):
    r.set(key, value)
    # 可选：为键设置过期时间
    r.expire(key, expire_time)

# 使用示例
# key = 'example_key'
# value = 'Hello, Redis Cache!'
#
# # 将数据写入缓存
# set_to_cache(key, value)
#
# # 从缓存中读取数据
# cached_value = get_from_cache(key)
# print(f'Retrieved from cache: {cached_value}')
#
# # 检查缓存中的键是否存在
# if r.exists(key):
#     print(f'Key "{key}" exists in the cache.')
# else:
#     print(f'Key "{key}" does not exist in the cache.')
#
# # 清除缓存中的键（可选）
# r.delete(key)
